"""
用户账户相关功能: 注册, 短信, 登陆, 注销
"""

from django.shortcuts import render, HttpResponse, redirect
from django.views.decorators.csrf import csrf_exempt

from web import models
from utils.code.code import check_code
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSmsModelForm, LoginCodeSmsModelForm
from django.http import JsonResponse
from django.conf import settings

from io import BytesIO
import datetime
from scripts import RandomStr

def register(request):
    """注册"""
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', {'form': form})

    # 数据校验
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 验证通过, 写入数据库 [ 自动剔除没用的数据 ] (密码加密)
        # 用户表中新建一条数据
        instance = form.save()
        # 价格策略
        policy_obj = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        # 创建交易记录
        models.Transaction.objects.create(
            status=2,
            # 订单号, 随机生成
            order=RandomStr.randomStr(),
            user=instance,
            price_policy=policy_obj,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now(),
        )

        return JsonResponse({"status": True, 'data': '/login/sms/'})
    return JsonResponse({"status": False, 'error': form.errors})


def send_sms(request):
    """发送短信"""

    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({"status": False, "error": form.errors})


"""
    注册按钮, 通过ajax发送请求, 错误信息, 数据库增加数据
    短信登陆
    django实现图片验证码
"""


@csrf_exempt
def login_sms(request):
    """短信登陆"""
    if request.method == 'GET':
        form = LoginSmsModelForm()
        return render(request, 'login_sms.html', {'form': form})
    form = LoginSmsModelForm(data=request.POST)
    if form.is_valid():
        # 用户输入正确, 登陆成功
        user_obj = form.cleaned_data.pop('user')
        # 将用户信息写入session
        request.session['user_id'] = user_obj.id
        request.session.set_expiry(60 * 60 * 24 * 7)
        return JsonResponse({"status": True, 'data': '/index/'})
    return JsonResponse({"status": False, 'error': form.errors})


def login_img_sms(request):
    """图片验证码"""
    # 用户名和密码登陆
    if request.method == 'GET':
        form = LoginCodeSmsModelForm(request)
        return render(request, 'login_img_sms.html', {"form": form})

    form = LoginCodeSmsModelForm(data=request.POST, request=request)
    if form.is_valid():

        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')

        # 数据库校验, 获取用户对象, 如果错误, 则为None
        # admin_obj = models.UserInfo.objects.filter(username=username, password=password).first()

        # (手机号=username, 密码=password) or (邮箱=username, 密码=password)
        from django.db.models import Q

        # 构造复杂的查询条件
        admin_obj = models.UserInfo.objects.filter(
            Q(username=username) | Q(mobile_phone=username) | Q(email=username),
            password=password
        ).first()
        if admin_obj:
            # 用户名和密码正确, 登陆成功
            # 将用户信息写入session
            request.session['user_id'] = admin_obj.id
            request.session.set_expiry(60 * 60 * 24 * 7)
            return redirect('/index/')
        form.add_error('username', '用户名或密码错误')
    # 校验失败, 返回错误信息
    return render(request, 'login_img_sms.html', {'form': form})


def image_code(request):
    """生成图像验证码"""
    # 调用PIL生成验证码图片
    img, code_str = check_code()

    # 写入到自己的session中, 以便后续获取验证码再进行校验
    request.session['image_code'] = code_str
    # [默认过期时间为2weeks] 设置60s超时
    request.session.set_expiry(60)

    # 将图片写入到内存中, 然后再返回
    stream = BytesIO()
    img.save(stream, 'png')
    # 将内存中的图片数据返回给客户端, MIMETYPE
    return HttpResponse(stream.getvalue())


def logout(request):
    # 注销
    request.session.flush()
    # 重定向到index
    return redirect('/index/')

